﻿using AutoMapper;
using B.S.Unit.Domain;
using B.S.Unit.ErrorCode;
using B.S.Unit.Infacet;
using B.S.Unit.Read.API.Applications.Command;
using MediatR;

namespace B.S.Unit.Read.API.Applications.CommandHandler
{
    public class GetUnitCommandHandler : IRequestHandler<GetUnitCommand, UnitPaging<UnitApp>>
    {
        private readonly IBaseRepository<UnitApp> UnitApp;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="purchaseRepo"></param>
        /// <param name="mapper"></param>
        public GetUnitCommandHandler(IBaseRepository<UnitApp> UnitApp)
        {
            this.UnitApp = UnitApp;
        }
        public Task<UnitPaging<UnitApp>> Handle(GetUnitCommand request, CancellationToken cancellationToken)
        {
            UnitPaging<UnitApp> result = new UnitPaging<UnitApp>();
            // 查询
            var linq = UnitApp.GetAll().Where(x => x.IsDeleted == false);

            // 修正条件判断，当输入不为空时进行过滤
            if (!string.IsNullOrEmpty(request.UnitAppCode))
            {
                linq = linq.Where(x => x.UnitAppCode == request.UnitAppCode);
            }
            if (!string.IsNullOrEmpty(request.UnitAppName))
            {
                linq = linq.Where(x => x.UnitAppName.Contains(request.UnitAppName));
            }

            // 分页
            result.TotalCount = linq.Count();
            result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            result.Lists = linq.OrderByDescending(x => x.UnitAppId)
                               .Skip((request.PageIndex - 1) * request.PageSize)
                               .Take(request.PageSize)
                               .ToList();

            // 返回
            return Task.FromResult(result);
        }
    }
}
